import { createWebHistory, createRouter } from 'vue-router';
import store from '../store/store';
import axios from '@/utils/http-utils';

const routerHistory = createWebHistory();
const router = createRouter({
    history: routerHistory,
    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('../views/home/index.vue')
        },
        {
            path: '/home',
            redirect: { name: 'home' }
        },
        {
            path: '/logout',
            redirect: '/'
        },
        {
            path: '/login',
            name: 'Login',
            component: () => import("@/views/login/index.vue"),
            meta: { redirectAlreadyLogin: true }
        },
        {
            path: '/signup',
            name: 'Signup',
            component: () => import("@/views/SignUp.vue")
        },
        {
            path: '/column/:id',
            name: 'ColumnDetail',
            component: () => import("@/views/columnDetail/index.vue")
        },
        {
            path: '/create',
            name: 'create',
            component: () => import('@/views/createPost/index.vue'),
            meta: { requireLogin: true }
        }, 
        {
            path: '/posts/:id',
            name: 'post',
            component: () => import('@/views/PostDetail/index.vue'),
        }
    ]
});

// 添加路由守卫
router.beforeEach((to, from, next) => {
    const { user, token } = store.state;
    const { requireLogin, redirectAlreadyLogin } = to.meta;
    if (!user.isLogin) {
        if (token) {
            axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            store.dispatch('fetchCurrentUser').then(() => {
                if (redirectAlreadyLogin) {
                    next('/');
                } else {
                    next();
                }
            }).catch((e) => {
                console.error(e);
                store.commit('logout');
                next('login');
            })
        } else  {
            if (requireLogin) {
                next('login');
            } else {
                next();
            }
        }
    } else {
        if (redirectAlreadyLogin) {
            next('/');
        } else {
            next();
        }
    }
    // to 即将进入的路由，from 从哪来
    // if (to.meta.requireLogin && !store.state.user.isLogin) {
    //     next({ name: 'login' });
    // } else if (to.meta.redirectAlreadyLogin && store.state.user.isLogin) {
    //     next('/');
    // } else {
    //     next();
    // }
})

export default router;